<?php
/**
 * 数据备份还原
 */
namespace Admin\Controller;

use Common\Controller\AdminbaseController;
use Think\Db;
use OT\Database;

class DatabaseController extends AdminbaseController {
	
	public function _initialize()
    {
        parent::_initialize();
        $this->backup_path = '/data/backup/';
        $this->_database_mod = M();
    }
	
	public function index($type = null){
		switch($type){
			case 'import':
				break;
			case 'export':
				break;
			default:
                $this->error('参数错误！');
		}
		
		$this->display($type);
	}
	
	//备份列表
	public function export(){		
		$db  = Db::getInstance();
        $list  = $db->query('SHOW TABLE STATUS');
		$list  = array_map('array_change_key_case', $list);	
		
		$this->assign('list',$list);
		$this->display();
	}
	
	//还原列表
	public function import(){
						
		$backups = array(); //所有的备份
        if (is_dir(SITE_PATH . $this->backup_path))
        {
            if ($handle = opendir(SITE_PATH . $this->backup_path))
            {
                while (($file = readdir($handle)) !== false)
                {				
					
                    if ($file{0} != '.' && filetype(SITE_PATH . $this->backup_path . $file) !== 'dir' && $file !== 'backup.lock')
                    {
                        $backup['name'] = $file;						
                        $backup['date'] = filemtime(SITE_PATH . $this->backup_path . $file);
                        $backup['date_str'] = date('Y-m-d H:i:s', $backup['date']);                    
                        $backup['total_size'] = $this->my_filesize(SITE_PATH . $this->backup_path . $file);
                        $backups[] = $backup;
                    }
                }
            }
        }
        arsort($backups);
		
		$this->assign('backups',$backups);
		$this->display();
	}
	
	//备份数据
	public function export_data($tables = null){
		if(IS_POST){			
			$file_name = date('Ymd-His',time());
			foreach($tables as $key=>$table){
				//$this->_get_table_data($table);
				//die;
				$get_table = $this->_get_table($table);
				
				//$get_table .= $this->_get_table_data($table);
				$result = $this->_database_mod->query("SELECT * FROM `{$table}` LIMIT 0, 1000");			
				foreach ($result as $row) {					   
						$row = implode("', '", $row);
						$get_table .= "INSERT INTO `{$table}` VALUES ('{$row}');\n";
										
					}
				$r = file_put_contents(SITE_PATH . $this->backup_path . $file_name . '.sql', $get_table,FILE_APPEND);
				
			}
			if($r !== false){
				$this->success('备份成功');
			}else{
				$this->error('备份失败');
			}
			
		}
		
	}
	
	private function _get_table($table){
		$table_df = "DROP TABLE IF EXISTS `$table`;\n";
        $tmp_sql = $this->_database_mod->query("SHOW CREATE TABLE `$table` ");
        //var_dump($tmp_sql);exit();
        $tmp_sql = $tmp_sql['0']['create table'];
        $tmp_sql = substr($tmp_sql, 0, strrpos($tmp_sql, ")") + 1); //去除行尾定义。
        $tmp_sql = str_replace("\n", "\r\n", $tmp_sql);
        $table_df .= $tmp_sql . " COLLATE='utf8_general_ci' ENGINE=MyISAM;\r\n";
        return $table_df;
	}
	
	private function _get_table_data($table){
		$result = $this->_database_mod->query("SELECT * FROM `{$table}` LIMIT 0, 1000");			
		foreach ($result as $row) {
               // $row = array_map('mysql_real_escape_string', $row);
				$row = implode("', '", $row);
                $sql = "INSERT INTO `{$table}` VALUES ('{$row}');\n";
				return $sql;				
            }
		
	}
	
	public function import_data(){
		if(isset($_GET['filename'])){
			$filename = I('get.filename');
									
			
			$sql_file = SITE_PATH . $this->backup_path . $filename . '.sql';
		
			$sql_str = file($sql_file);
			$sql_str = preg_replace("/^--.+\n/",'', $sql_str);
			$sql_str = str_replace("\r", '', implode('', $sql_str));      
			$ret = explode(";\n", $sql_str);
			$ret_count = count($ret);
			
			
			for ($i = 0; $i < $ret_count; $i++)
			{
				$ret[$i] = trim($ret[$i], " \r\n;"); //剔除多余信息
				
				if (!empty($ret[$i]))
				{
				   $import = $this->_database_mod->execute($ret[$i]);				   
				}
			}
			unlink(SITE_PATH . $this->backup_path . 'backup.lock');
			if($import !== false){
				$this->success('还原成功');
			}else{
				$this->error('还原失败');
			}
		}
		
	}
	
	//删除备份文件
	public function del_backup(){
		if(isset($_GET['backup'])){
			$filename = I('get.backup');
			$sql_file = SITE_PATH . $this->backup_path . $filename . '.sql';
			if(!file_exists($sql_file)){
				$this->error('文件不存在');
			}else{
				if(unlink($sql_file) !== false){
					$this->success('删除成功');
				}else{
					$this->error('删除失败');
				}
			}
		}
	}
	
	//优化表
	public function optimize($tables = null){
		$Db   = Db::getInstance();
		if($_GET['tablename']){
			$tablename = I('get.tablename');
			$list = $Db->query("OPTIMIZE TABLE `{$tablename}`");
                if($list){
                    $this->success("数据表'{$tablename}'优化完成！");
                } else {
                    $this->error("数据表'{$tablename}'优化出错请重试！");
                }
		}
		if(IS_POST){
			if($tables) {
				if(is_array($tables)){
					$tables = implode('`,`', $tables);
					$list = $Db->query("OPTIMIZE TABLE `{$tables}`");

					if($list){
						$this->success("数据表优化完成！");
					} else {
						$this->error("数据表优化出错请重试！");
					}
				}
			} else {
				$this->error("请指定要优化的表！");
			}
		}
		
    }
	
	//修复表
	public function repair($tables = null){
		$Db   = Db::getInstance();
		if($_GET['tablename']){
			$tablename = I('get.tablename');
			$list = $Db->query("REPAIR TABLE `{$tablename}`");
            if($list){
                $this->success("数据表'{$tablename}'修复完成！");
            } else {
                $this->error("数据表'{$tablename}'修复出错请重试！");
			}
		}
		
		if(IS_POST){
			if($tables) {
				
				if(is_array($tables)){
					$tables = implode('`,`', $tables);
					$list = $Db->query("REPAIR TABLE `{$tables}`");

					if($list){
						$this->success("数据表修复完成！");
					} else {
						$this->error("数据表修复出错请重试！");
					}
				} 
			} else {
				$this->error("请指定要修复的表！");
			}
		}
    }
	
	//文件大小
	function my_filesize($filename){
		$str='';
		$num=filesize($filename);
		if($num<1024){
			$str=$num.'B';
		}else if($num>=1024 && $num<pow(2,20)){
			$str=sprintf('%.1fKB',$num/1024);
		}else if($num>=pow(2,20) && $num<pow(2,30)){
			$str=sprintf('%.1fMB',$num/pow(2,20));
		}else if($num>=pow(2,30) && $num<pow(2,40)){
			$str=sprintf('%.1fGB',$num/pow(2,30));
		}else if($num>=pow(2,40) && $num<pow(2,50)){
			$str=sprintf('%.1fTB',$num/pow(2,40));
		}
		return $str;
	}
		
}